const express = require('express');
const multer = require('multer');
const fs = require('fs-extra');
const path = require('path');
const nodemailer = require('nodemailer');
const crypto = require('crypto'); // 使用 Node.js 内置的 crypto 模块

const app = express();
let port = 13008;




// 中间件
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// 用户数据存储
const usersFilePath = path.join(__dirname, 'data', 'users.json');
const uploadsDir = path.join(__dirname, 'data', 'uploads');
const projectFilePath = path.join(__dirname, 'data', 'projects.json');

// 读取用户数据
async function readUsers() {
    try {
        const data = await fs.readFile(usersFilePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        return [];
    }
}

// 写入用户数据
async function writeUsers(users) {
    await fs.writeFile(usersFilePath, JSON.stringify(users, null, 2));
}

// 配置 nodemailer
const transporter = nodemailer.createTransport({
    service: 'Gmail', // 使用 Gmail 作为邮件服务
    auth: {
        user: '820749789@qq.com', // 替换为你的邮箱
        pass: '820749789' // 替换为你的邮箱密码
    }
});

// 发送验证码
app.post('/send-verification-code', async (req, res) => {
    const { email } = req.body;
    if (!email) {
        return res.status(400).send('邮箱不能为空');
    }

    // 生成验证码
    const verificationCode = crypto.randomBytes(5).toString('hex');

    // 发送邮件
    const mailOptions = {
        from: '"云存储库" 820749789@qq.com', // 发件人
        to: email, // 收件人
        subject: '邮箱验证码',
        text: `你好！\n\n你的邮箱验证码为: ${verificationCode}\n\n请在注册页面填写此验证码以完成注册。`
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            console.error('邮件发送失败:', error);
            return res.status(500).send('邮件发送失败');
        }
        console.log('邮件发送成功:', info.response);
        res.status(200).json({ verificationCode });
    });
});

// 注册
app.post('/register', async (req, res) => {
    const { username, password, email, verificationCode } = req.body;
    const hashedPassword = crypto.createHash('md5').update(crypto.createHash('md5').update(password).digest('hex')).digest('hex');
    const users = await readUsers();

    // 检查邮箱是否已存在
    if (users.some(user => user.email === email)) {
        return res.status(400).send('邮箱已存在');
    }

    // 检查用户名是否已存在
    if (users.some(user => user.username === username)) {
        return res.status(400).send('用户名已存在');
    }

    // 检查验证码是否正确
    if (!verificationCode || verificationCode !== req.session.verificationCode) {
        return res.status(400).send('验证码错误');
    }

    const newUser = { username, password: hashedPassword, email, avatar: 'default-avatar.png', repositories: [], role: 'default' };
    users.push(newUser);
    await writeUsers(users);
    res.status(200).send('注册成功');
});

// 登录
app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const users = await readUsers();
    const hashedPassword = crypto.createHash('md5').update(crypto.createHash('md5').update(password).digest('hex')).digest('hex');
    const user = users.find(user => user.username === username && user.password === hashedPassword);
    if (user) {
        res.status(200).json(user);
    } else {
        res.status(401).send('无效的用户名或密码');
    }
});

// 重置密码
app.post('/reset-password', async (req, res) => {
    const { email, verificationCode, newPassword } = req.body;
    const users = await readUsers();
    const user = users.find(user => user.email === email);

    if (!user) {
        return res.status(400).send('邮箱不存在');
    }

    // 检查验证码是否正确
    if (!verificationCode || verificationCode !== req.session.verificationCode) {
        return res.status(400).send('验证码错误');
    }

    const hashedNewPassword = crypto.createHash('md5').update(crypto.createHash('md5').update(newPassword).digest('hex')).digest('hex');
    user.password = hashedNewPassword;
    await writeUsers(users);
    res.status(200).send('密码重置成功');
});

// 配置 multer 存储
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const { username, repositoryName } = req.body;
        const repoDir = path.join(uploadsDir, username, repositoryName);
        fs.ensureDirSync(repoDir);
        cb(null, repoDir);
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});

const upload = multer({ storage: storage });

// 上传文件
app.post('/upload', upload.array('files'), async (req, res) => {
    const { username, repositoryName } = req.body;
    const users = await readUsers();
    const user = users.find(user => user.username === username);
    if (!user.repositories.some(repo => repo.name === repositoryName)) {
        user.repositories.push({ name: repositoryName, files: req.files.map(file => file.originalname), uploadDate: new Date().toISOString().split('T')[0] });
        await writeUsers(users);
        res.status(200).send('文件上传成功');
    } else {
        res.status(400).send('存储库名称已存在');
    }
});

// 下载文件
app.get('/download/:username/:repositoryName/:filename', (req, res) => {
    const { username, repositoryName, filename } = req.params;
    const filePath = path.join(uploadsDir, username, repositoryName, filename);
    res.download(filePath, decodeURIComponent(filename), (err) => {
        if (err) {
            console.error('文件下载失败:', err);
            res.status(500).send('文件下载失败');
        }
    });
});

// 获取用户存储库信息
app.get('/repositories/:username', async (req, res) => {
    const { username } = req.params;
    const users = await readUsers();
    const user = users.find(user => user.username === username);
    res.status(200).json(user.repositories);
});

// 输出消息
app.get('/output/message/:message', async (req, res) => {
    const { message } = req.params;
    console.log(message);
    res.status(200).json(null);
});
// 删除存储库
app.delete('/repositories/:username/:repositoryName', async (req, res) => {
    const { username, repositoryName } = req.params;
    const users = await readUsers();
    const user = users.find(user => user.username === username);
    const repoIndex = user.repositories.findIndex(repo => repo.name === repositoryName);
    if (repoIndex !== -1) {
        const repoDir = path.join(uploadsDir, username, repositoryName);
        await fs.remove(repoDir);
        user.repositories.splice(repoIndex, 1);
        await writeUsers(users);
        res.status(200).send('存储库已成功删除');
    } else {
        res.status(404).send('存储库未找到');
    }
});

// 删除文件
app.delete('/repositories/:username/:repositoryName/:filename', async (req, res) => {
    const { username, repositoryName, filename } = req.params;
    const users = await readUsers();
    const user = users.find(user => user.username === username);
    const repo = user.repositories.find(repo => repo.name === repositoryName);
    if (repo) {
        const fileIndex = repo.files.indexOf(filename);
        if (fileIndex !== -1) {
            const filePath = path.join(uploadsDir, username, repositoryName, filename);
            await fs.remove(filePath);
            repo.files.splice(fileIndex, 1);
            await writeUsers(users);
            res.status(200).send('文件已成功删除');
        } else {
            res.status(404).send('文件未找到');
        }
    } else {
        res.status(404).send('存储库未找到');
    }
});


// 获取所有用户（仅限管理员）
app.get('/users', async (req, res) => {
    const users = await readUsers();
    const currentUser = JSON.parse(req.headers.authorization || '{}');
    if (currentUser.role === 'root') {
        res.status(200).json(users);
    } else {
        res.status(403).send('您没有权限');
    }
});
// 切换用户（仅限管理员）
app.post('/switch-user', async (req, res) => {
    const { username } = req.body;
    const users = await readUsers();
    const user = users.find(user => user.username === username);
    if (user) {
        res.status(200).json(user);
    } else {
        res.status(404).send('用户未找到');
    }
});
// 更新用户信息
app.post('/update-user', async (req, res) => {
    const { username, ...updates } = req.body;
    const users = await readUsers();
    const userIndex = users.findIndex(user => user.username === username);
    if (userIndex === -1) {
        return res.status(404).send('用户未找到');
    }

    const user = users[userIndex];
    Object.assign(user, updates);
    await writeUsers(users);
    res.status(200).json(user);
});

// 添加 404 页面处理
app.use((req, res) => {
  res.status(404).send(`
        <!DOCTYPE html>
        <html lang="en">
            <head>
            <title>404</title>
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
        </head>
        <h1>无此页面</h1>
        <h2>3秒返回首页</h2>
        <script>
            window.setTimeout(()=>{
                location.href="/";
            },3000)
        </script>
  `);
});

// 处理个人资料更新
app.post('/update-profile', async (req, res) => {
  const currentUser = JSON.parse(req.headers.authorization || '{}');
  const { username, email, password } = req.body;
  const users = await readUsers();

  // 检查用户名是否已存在（除了当前用户）
  if (users.some(user => user.username === username && user.username !== currentUser.username)) {
      return res.status(400).send('用户名已存在');
  }

  // 检查邮箱是否已存在（除了当前用户）
  if (users.some(user => user.email === email && user.email !== currentUser.email)) {
      return res.status(400).send('邮箱已存在');
  }

  // 找到当前用户
  const userIndex = users.findIndex(user => user.username === currentUser.username);
  if (userIndex === -1) {
      return res.status(404).send('用户未找到');
  }

  // 更新用户信息
  const user = users[userIndex];
  user.username = username;
  user.email = email;
  if (password) {
      user.password = hashPassword(password);
  }

  // 处理头像上传
  if (req.files && req.files.avatar) {
      const avatarFile = req.files.avatar[0];
      const avatarPath = path.join(uploadsDir, username, 'avatar.png');
      await fs.ensureDir(path.dirname(avatarPath));
      await fs.move(avatarFile.path, avatarPath, { overwrite: true });
      user.avatar = `/uploads/${username}/avatar.png`;
  }

  // 保存更新后的用户数据
  await writeUsers(users);

  res.status(200).json(user);
});

app.post('/api/save-notice', (req, res) => {
    const content = req.body.content;
    fs.writeFileSync(path.join(__dirname, 'data', 'index.html'), content, 'utf8');
    res.json({ success: true, message: '公告保存成功' });
});

app.get('/api/get-notice', (req, res) => {
    const data = fs.readFileSync(path.join(__dirname, 'data', 'index.html'), 'utf8');
    res.send(data);
});

let data = JSON.parse(await fs.readFile(projectFilePath, 'utf8'));
port = data.port;

// 启动服务器
app.listen(port, () => {
    console.log(`日志: \n`);
    console.log(`网站为http://localhost:${port}/`);
});